﻿<%@ Page Language="C#" %>

<script language="c#" runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        string typeName = Request.Params["class"];
        string methodName = Request.Params["method"];
        string args = Request.Params["params"];

        Response.Write(WebInvoke.Invoke(typeName, methodName, args));
    }

    [WebInvokeClass]
    public class InvokeDemo
    {
        //[WebInvokeMethod] //If this class is not marked as WebInvokeClass, then WebInvokeMethod is required.
        public static string HelloWorld(string name, string words)
        {
            string result;
            string text = "Hello world, hello " + name+ "! " + words + " " + DateTime.Now;
            
            System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
            result = json.Serialize(new Pair(text, null));

            return result;
        }
    }

    public class WebInvokeClassAttribute : Attribute
    {
    }

    public class WebInvokeMethodAttribute : Attribute
    {
    }

    public static class WebInvoke
    {
        public static string Invoke(string typeName, string methodName, string args)
        {
            if (String.IsNullOrEmpty(typeName))
                throw new ArgumentNullException("typeName");
            
            if (String.IsNullOrEmpty(methodName))
                throw new ArgumentNullException("methodName");
            
            string result = null;
            Type type = Type.GetType(typeName);
            System.Reflection.MethodInfo method = type.GetMethod(methodName);
            string[] methodArgs = args != null ? args.Split(',') : null;

            //if (HttpContext.Current.Request.IsAuthenticated)
                if (Attribute.IsDefined(type, typeof(WebInvokeClassAttribute), true) ||
                    Attribute.IsDefined(method, typeof(WebInvokeMethodAttribute), true))
                {
                    try
                    {
                        result = (method.Invoke(null, methodArgs) ?? String.Empty).ToString();
                    }
                    catch(Exception ex)
                    {
                    }
                }

            return result;
        }
    }
</script>